/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.webflux.web;

import com.luter.heimdall.core.context.WebContextHolder;
import com.luter.heimdall.core.context.WebRequestHolder;
import com.luter.heimdall.core.context.WebResponseHolder;
import com.luter.heimdall.core.exception.HeimdallException;
import org.slf4j.Logger;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * WebFlux 上下文持有者实现
 * <p>
 * 用以获取 request 和 response
 *
 * @author luter
 */
public class WebFluxWebContextHolder implements WebContextHolder {
    private static final transient Logger log = getLogger(WebFluxWebContextHolder.class);

    @Override
    public WebRequestHolder getRequest() {
        log.debug("[getRequest]::");
        final ServerHttpRequest request = WebFluxContextThreadLocalUtil.getRequest();
        if (null == request) {
            throw new HeimdallException("Not a valid ServerHttpRequest context," +
                    "ReactiveWebRequestHolder initialized failed");
        }

        return new ReactiveWebRequestHolder(request);
    }

    @Override
    public WebResponseHolder getResponse() {
        log.debug("[getResponse]::");
        final ServerHttpResponse response = WebFluxContextThreadLocalUtil.getResponse();
        if (null == response) {
            throw new HeimdallException("Not a valid ServerHttpRequest context," +
                    "ReactiveWebResponseHolder initialized failed");
        }
        return new ReactiveWebResponseHolder(response);
    }
}
